package com.identify.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.identify.mapper.UserMapper;
import com.identify.pojos.dtos.AppUserLoginDto;
import com.identify.pojos.dtos.UserLoginDto;
import com.identify.pojos.entity.User;
import com.identify.pojos.vos.WxLoginGetVo;
import com.identify.properties.WeChatProperties;
import com.identify.service.UserService;
import com.identify.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.identify.constant.MessageConstant;
import org.apache.commons.lang3.StringUtils;
import cn.hutool.crypto.digest.BCrypt;
import com.identify.pojos.dtos.UserRegisterDto;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private HttpClientUtil httpClientUtil;

    /**
     * 测试用户方法
     * @return
     */
    @Override
    public List<User> userTest() {
        return userMapper.selectList(null);
    }

    /**
     * 微信登录
     * @param dto
     * @return
     */
    @Override
    public User wxLogin(UserLoginDto dto) {

        //调用微信接口，获取用户openid
        String openid = getOpenId(dto.getCode());

        //判断openid是否空
        if(openid == null) {
            throw new RuntimeException("微信登录失败! openid为null");
        }

        //判断当前用户是否为新用户（是否查询到了用户）
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openid));

        //如果是新用户，自动注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .username("微信用户")
                    .build();
            userMapper.insert(user);
        }

        //返回用户对象
        return user;
    }

    /**
     * 用户注册
     * @param dto
     */
    @Override
    public void register(UserRegisterDto dto) {
        //查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,dto.getUsername());
        User user = userMapper.selectOne(wrapper);
        //用户存在，抛出异常
        if(user != null){
            throw new RuntimeException("用户名已存在");
        }
        //用户不存在，封装数据，插入数据
        user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(dto.getPassword());
        user.setCreateTime(LocalDateTime.now());

        this.save(user);

    }

    /**
     * app登录
     * @param dto
     * @return
     */
    @Override
    public User login(AppUserLoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();

        //根据用户名查询数据库中的数据
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(wrapper);

        //处理各种异常情况
        if (user == null){
            //账号不存在
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        if (!BCrypt.checkpw(password,user.getPassword())){
            //密码错误
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }

        //返回用户对象
        return user;
    }

    @Override
    public boolean save(User entity) {
        if(StringUtils.isNotEmpty(entity.getPassword())){
            entity.setPassword(BCrypt.hashpw(entity.getPassword()));
        }
        return super.save(entity);
    }

    @Override
    public boolean updateById(User entity) {
        if(StringUtils.isNotEmpty(entity.getPassword())){
            entity.setPassword(BCrypt.hashpw(entity.getPassword()));
        }
        return super.updateById(entity);
    }

    /**
     * 获取微信用户openid
     * @param code
     * @return
     */
    private String getOpenId(String code) {

        //构建wx接口请求参数
        Map<String, String> map = new HashMap<>();

        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + weChatProperties.getAppid() + "&secret=" + weChatProperties.getSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        WxLoginGetVo vo = httpClientUtil.doGet(wxLoginUrl, map);

        String openid = vo.getOpenid();

        return openid;
    }
}
